package com.baizhi.service.impl;


import com.baizhi.entity.CmfzAdmin;
import com.baizhi.mapper.CmfzRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service("ps")
public class PermissionService {

    @Autowired
    private CmfzRoleMapper cmfzRoleMapper;

    public boolean hasRole(String role){
        return hasAnyRole(role);
    }

    public boolean hasAnyRole(String... roles){
        Set<String> allRoles = cmfzRoleMapper.getAllRolesByUsername(getUsername());
        for (String role : roles) {
            if (allRoles.contains(role)){
                return true;
            }
        }
        return false;
    }

    public boolean hasPermission(String permission){
        return hasAnyPermission(permission);
    }
    public boolean hasAnyPermission(String... permissions){

        Set<String> allPermissions = cmfzRoleMapper.getAllPermissionsByUsername(getUsername());
        for (String permission : permissions) {
            if (allPermissions.contains(permission)){
                return true;
            }
        }
        return false;
    }


    /**
     * 获取当前认证的用户的用户名
     */
    public String getUsername(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        System.out.println(principal);
        CmfzAdmin cmfzAdmin= (CmfzAdmin) principal;
        return cmfzAdmin.getUsername();
    }

}
